import { getColumns,saveModel,getModel,getSampleList } from '@/axios/api.js'
import { dateFormat,RANDOM,sleep,base64ToBlob,groupBy } from '@/utils/functions.js'
import { nodeInfo } from '../conf/nodes.js'
import { menuList } from '@/conf.js'
import { getStore,setStore,removeStore } from '@/utils/StoreOpers'
// import { asinh } from 'core-js/library/fn/number'
export default {
  data(){
    return {
      runing:false,
      modeSample:{},
      modelInfo:{},
      columnsData:false,//列数据
      all_columnsData:[],
      searchLoading:false,
      searchChange:this._debounce(async ({target:{_value:value}}) => {
        this.searchLoading = true
        if(!value) this.columnsData = this.all_columnsData
        else {
          this.columnsData = this.all_columnsData.filter(e=>
            e.name.toLowerCase().indexOf(value.toLowerCase()) >= 0
          )
        }
        await this.$nextTick()
        await sleep(400)
        this.searchLoading = false
      },1000),
      resultListSave:{},//缓存pdf
      resultnode:{},
      islocal:false
    }
  },
  inject:['reload'],
  props:['modeid','modename'],
  async created(){
    let { modename,modeid } = this
    const { nodeList,lineList } = nodeInfo(modename)
    nodeList.map((e,i) => {
      e.top = `${(Math.floor(i/4)+1)*200}px`
      e.left = `${i%4*300+100}px`
      // e.top = `${i*100+100}px`
      // e.left = `${i%2*400+200}px`
      e.status = 0
      e.receive = false
    })
    this.nodeList = nodeList
    this.lineList = Object.freeze(lineList)
    await getSampleList().then(e=>{
      const result = groupBy(e.data.sampleList,e=>e.type? "报文组抽取":"用户导入")
      this.sampleList = result
      console.log(result)
    })
    if(!modeid){
      try{
        const { modelInfo:modelInfo_stora } = getStore(modename)
        if(modelInfo_stora){
          modeid = modelInfo_stora.id
          this.modelInfo = modelInfo_stora
          this.islocal = true
        }
      }catch(e){/*无缓存*/}
    }
    if(modeid){
      const msg = this.$message.loading('模型恢复中...', 0)
      await getModel({id:modeid}).then(async e=>{
        const {data:{modelInfo,modelSample,confJson,resultnode}} = e
				let { data:{RUNING_TAG} } = e
				RUNING_TAG = JSON.parse(RUNING_TAG)
        console.log({modelInfo,modelSample,RUNING_TAG,confJson,resultnode})
        // if(modelSample && modelSample.id)
        	// await this.chooseModeSample(modelSample,true,true)
        // else{
          const { sampleList } = this
          const { sampleId } = confJson[0] || modelInfo
          if(sampleId){
          	const item = [...sampleList['"报文组抽取"'],...sampleList['"用户导入"']].find(e=>e.id === sampleId)
          	if(!item) this.$message.error('原样本集已删除')
          	else await this.chooseModeSample(item,true,true)
          }
        // }
        if(modelInfo && modelInfo.id) this.modelInfo = modelInfo
        // await this.chooseModeSample(modelSample)
        // this.modelInfo = modelInfo
        this.allconf = confJson//computed:set
        if(RUNING_TAG && RUNING_TAG.length)
          RUNING_TAG.map((tag,module)=>{
            module += 1
            const status = tag===true? 2:tag===false? 3:0
            this.changeStatus({module,status})
          })
        if(resultnode){
          const file = await base64ToBlob({b64data:resultnode,contentType:'application/pdf'})
          const url = file.preview
          await this.addResultNode(url)
        }
      }).catch(e=>{
        console.log(e)
        this.$message.error('恢复模型异常')
      }).then(()=>{msg()})
    }else{
      const id = (new Date()-1)+String(RANDOM(4))
      this.modelInfo = {
        id,
        name: modename+'模型-'+String(new Date()-1),
        description: null,
        createTime:dateFormat('Y-M-D h:m:s',new Date()),
        saveTime:null,
      }
    }
  },
  async mounted(){
    await this.$nextTick()
    this.init()
  },
  methods:{
    changeDel(tag){
      this.columnsData.map(e=>e.del=tag)
    },
    mackNew(){
      this.$confirm({
        title: '创建新模型',
        content: h => <div>将<span style="color:red;">删除</span>当前缓存中的内容，创建一个新的模型，确定要继续吗？</div>,
        onOk:()=>{
          removeStore(this.modename)
          if(this.modeid)
            this.$router.push({query:{}})
          this.reload()
          // this.$router.go(0)
        },
        okText:'确认',
        cancelText:'取消',
        okType:'danger'
      });
    },
    async chooseModeSample(item,reset,recover){
      if(item.id === this.modeSample.id && !reset) return
      this.columnsData = false
      this.changeStatus({status:1,module:0})
      this.modeSample = this._cloneDeep(item)
      const { id } = item
      await getColumns({id}).then(e=>{
        const { columns } = e.data
        this.all_columnsData = columns.map(name=>{
          return {name,del:0,role:1}
        })
        if(!recover){//非恢复
          this.all_columnsData[0].role=0
          this.all_columnsData[this.all_columnsData.length - 1].role=2
        }
        // this.all_columnsData = this._cloneDeep(columns)
        this.columnsData = this.all_columnsData
        const firstnode = this.nodeList.find(e=>e.module===1)
        // const status = (||runtag)? 2:-1
        if(firstnode.status != 0)
          this.changeStatus({status:-1,module:0})
        this.changeStatus({status:2,module:0})
      }).catch(e=>{
        console.log(e)
        this.changeStatus({status:3,module:0})
      })
    },
    async MODEL_SAVE(){
      this.$message.loading({content:"保存模型",duration:0,key:"SAVE_LOADING"})
      const confJSON = await this.GET_CONF()
      const { modelInfo,modename,modeSample } = this
      const type = await menuList.indexOf(modename)
      console.log({menuList,modename})
      debugger
      const { id:sampleId } = modeSample
      const POST_DATA = Object.assign(modelInfo,{type,sampleId},{confJSON:JSON.stringify(confJSON)})
      await saveModel(POST_DATA)
      this.modelInfo.saveTime = dateFormat('Y-M-D h:m:s',new Date())
      this.$message.success({content:"保存成功",key:"SAVE_LOADING"})
    }
  }
}